<template>

	<view v-if="type=='video'">
		<view v-if="bigBg" class="gui-idcard-items-image">
			<view v-if="bg" class="gui-relative">
				<gui-image :src="bg" :width="380"></gui-image>
				<text class="gui-add-list-remove gui-icons gui-absolute-rt" @tap="removeBg">&#xe632;</text>
			</view>
			<video v-else :src="bigBg" :width="380" @tap="addImg"></video>
		</view>

		<view v-else class="gui-bg-white gui-dark-bg-level-3">
			<hyb-video-choose :maxFileNumber="maxFileNumber" @change="change" :items="items">
			</hyb-video-choose>
		</view>
	</view>


	<view v-else>
		<view v-if="bigBg" class="gui-idcard-items-image">
			<view v-if="bg" class="gui-relative">
				<gui-image :src="bg" :width="380"></gui-image>
				<text class="gui-add-list-remove gui-icons gui-absolute-rt" @tap="removeBg">&#xe632;</text>
			</view>
			<gui-image v-else :src="bigBg" :width="380" @tap="addImg"></gui-image>
		</view>

		<view v-else class="gui-bg-white gui-dark-bg-level-3">
			<gui-choose-images v-if="!hide" :btnName="label" :maxFileNumber="maxFileNumber" @change="change"
				:items="items">
			</gui-choose-images>
		</view>

	</view>
</template>

<script>
	export default {
		name: "hyb-upload",
		props: {
			hide: {
				type: Boolean,
				default: false
			},

			type: {
				type: String,
				default: "image"
			},

			label: {
				type: String,
				default: "上传图片"
			},

			bigBg: {
				type: String,
				default: ""
			},

			maxFileNumber: {
				type: Number,
				default: 1
			},
			modelValue: {
				type: [String, Array],
				default: ""
			}
		},
		data() {
			return {
				items: [],
				files: [],
				urls: [],
				bg: "",
			};
		},
		watch: {
			modelValue: function() {
				this.initImgs();
			}
		},
		created() {
			this.initImgs();
		},



		methods: {

			removeBg() {
				this.bg = "";
				this.files = [];
			},

			addImg: function() {

				// #ifdef MP-WEIXIN
				uni.chooseMedia({
					mediaType: "image",
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log(res)
						this.bg = res.tempFiles[0].tempFilePath;
						this.files.push({
							url: res.tempFiles[0].tempFilePath,
							progress: 0,
							name: res.tempFiles[0].name,
							flag: 1
						});
						console.log(this.files)
					},
					complete: function() {}
				});
				// #endif

				// #ifndef MP-WEIXIN
				uni.chooseImage({
					mediaType: "image",
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						console.log(res)
						this.bg = res.tempFilePaths[0];
						this.files.push({
							url: res.tempFilePaths[0],
							progress: 0,
							name: res.tempFiles[0].name,
							flag: 1
						});
						console.log(this.files)
					},
					complete: function() {}
				});
				// #endif

			},
			initImgs() {
				if (this.modelValue) {
					let that = this;
					setTimeout(() => {
						that.items = [];
						that.files = [];
						if (that.maxFileNumber > 1 || that.modelValue instanceof Array) {
							that.modelValue.forEach((url) => {
								that.items.push(url)
								that.files.push({
									url: url
								})
							})
						} else {
							if (!that.bigBg) {
								that.items.push(that.modelValue)
								that.files.push({
									url: that.modelValue
								})
							} else {
								that.bg = that.modelValue;
								that.files.push({
									url: that.modelValue
								})
							}


						}
					})
				}
			},
			change(files) {
				console.log(files)
				this.files = files;
			},

			removeImg(files) {
				this.files = files;
			},


			uploadAsync(file) {
				console.log(file)
				let that = this
				if (file) {
					this.items = []
					this.urls = []
					this.files = []
					this.files.push(file)
				}
				return new Promise((resolve) => {
					this.upload(() => {
						resolve(that.urls)
					})
				})
			},


			upload(callback, index) {
				console.log(this.files.length, index);
				let that = this;
				if (index == undefined) {
					index = 0;
					this.urls = [];
				} else {
					index++;
				}

				if (that.files.length == 0) {

					if (that.maxFileNumber == 1 || that.bigBg) {
						that.$emit('input', that.urls[0])
						that.$emit('update:modelValue', that.urls[0])
					} else {
						that.$emit('input', that.urls)
						that.$emit('update:modelValue', that.urls)
					}

					if (callback) callback();
					return;
				}

				if (index >= that.files.length) {
					setTimeout(() => {
						if (this.urls.length > 0) {
							if (that.maxFileNumber == 1 || that.bigBg) {
								that.$emit('input', that.urls[0])
								that.$emit('update:modelValue', that.urls[0])
							} else {
								that.$emit('input', that.urls)
								that.$emit('update:modelValue', that.urls)
							}
						}
						if (callback) callback();
					})
					return;
				};
				let file = that.files[index];
				if (!file.name && file.flag) {
					file.name = file.url;
				}
				if (file.name) {
					let lastIndex = file.name.lastIndexOf('.');
					let ext = lastIndex > -1 ? file.name.slice(lastIndex + 1) : '';
					that.getUploadInfo(ext, (err, info) => {
						if (err) {
							that.upload(callback, index)
						} else {
							info.filePath = file.url;
							console.log(info.filePath)
							that.uploadFile(info, function(err, fileUrl) {
								if (!err) {
									that.urls.push(fileUrl)
								}
								that.upload(callback, index);
							});
						}

					})
				} else {
					that.urls.push(file.url);
					that.upload(callback, index);
				}
			},

			uploadFile(opt, callback) {
				var formData = {
					key: opt.cosKey,
					policy: opt.policy, // 这个传 policy 的 base64 字符串
					success_action_status: 200,
					'q-sign-algorithm': opt.qSignAlgorithm,
					'q-ak': opt.qAk,
					'q-key-time': opt.qKeyTime,
					'q-signature': opt.qSignature,
				};
				// 如果服务端用了临时密钥计算，需要传 x-cos-security-token
				if (opt.securityToken) formData['x-cos-security-token'] = formData.securityToken;
				uni.uploadFile({
					url: 'https://' + opt.cosHost, //仅为示例，非真实的接口地址
					filePath: opt.filePath,
					name: 'file',
					formData: formData,
					success: (res) => {
						console.log(res)
						if (![200, 204].includes(res.statusCode)) return callback && callback(res);
						var fileUrl = 'https://' + opt.cosHost + '/' + opt.cosKey
							.replace(/%2F/g, '/');
						callback && callback(null, fileUrl);
					},
					error(err) {
						callback && callback(err);
					},
				});
			},

			getUploadInfo(ext, callback) {
				// 传入文件后缀，让后端生成随机的 COS 对象路径，并返回上传域名、PostObject 接口要用的 policy 签名
				// 参考服务端示例：https://github.com/tencentyun/cos-demo/server/post-policy/

				let now = Math.round(Date.now() / 1000);
				let exp = now + 900;
				let expiration = new Date(exp * 1000).toISOString();
				uni.gPost("policy", {
					now: now,
					exp: exp,
					expiration: expiration,
					ext: ext
				}).then((data) => {
					console.log(data)
					callback && callback(null, data);
				})
			},

		}
	}
</script>

<style>
</style>